﻿using System;

using System.Collections;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;


using Guifreaks.Navisuite;

using Global.Class.Library;
using BusinessLogicLayer;
using DataAccessLayer;
using System.Globalization;

using BrightIdeasSoftware;
using RKLib.ExportData;

using OfficeExcel = Microsoft.Office.Interop.Excel;


namespace PresentationLayer
{
    public partial class MarketingMonitoring : Form, IMergeToolStrip, ICallToolStrip
    {

        [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
        public static extern int SetWindowTheme(IntPtr hWnd, String pszSubAppName, String pszSubIdList);

        #region <Implement Interface>

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public GlobalEnum.TaskID TaskID
        {
            get { return this.marketingMonitoringBLL.TaskID; }
        }


        public ToolStrip ChildToolStrip
        {
            get
            {
                return this.toolStripChildForm;
            }
            set
            {
                this.toolStripChildForm = value;
            }
        }





        #region Context toolbar


        public bool IsDirty
        {
            get { return this.marketingMonitoringBLL.IsDirty; }
        }

        public bool IsValid
        {
            get { return true; }
        }

        public bool Closable
        {
            get { return true; }
        }

        public bool Loadable
        {
            get { return true; }
        }

        public bool Newable
        {
            get { return false; }
        }

        public bool Editable
        {
            get { return false; }
        }

        public bool Deletable
        {
            get { return false; }
        }

        public bool Importable
        {
            get { return false; }
        }

        public bool Exportable
        {
            get { return true; }
        }

        public bool Verifiable
        {
            get { return false; }
        }

        public bool Unverifiable
        {
            get { return false; }
        }

        public bool Printable
        {
            get { return false; }
        }

        public bool Searchable
        {
            get { return true; }
        }

        /// <summary>
        /// Edit Mode: True, Read Mode: False
        /// </summary>
        private bool editableMode;
        private int lastMarketingMonitoringID;
        public bool EditableMode { get { return this.editableMode; } }
        /// <summary>
        /// This reverse of the EditableMode
        /// </summary>
        public bool ReadonlyMode { get { return !this.editableMode; } }

        /// <summary>
        /// Set the editableMode
        /// </summary>
        /// <param name="editableMode"></param>
        private void SetEditableMode(bool editableMode)
        {
            if (this.editableMode != editableMode)
            {
                this.lastMarketingMonitoringID = this.marketingMonitoringBLL.MarketingMonitoringID;
                this.editableMode = editableMode;
                this.NotifyPropertyChanged("EditableMode");
            }
        }


        private void CancelDirty(bool restoreSavedData)
        {
            try
            {
                if (restoreSavedData || this.marketingMonitoringBLL.MarketingMonitoringID <= 0)
                    this.marketingMonitoringBLL.Fill(this.lastMarketingMonitoringID);

                this.SetEditableMode(false);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }



        #endregion Context toolbar



        #region ICallToolStrip

        public void Escape()
        {
            if (this.EditableMode)
            {
                if (this.IsDirty)
                {
                    DialogResult dialogResult = MessageBox.Show(this, "Do you want to save your change?", "Warning", MessageBoxButtons.YesNoCancel);
                    if (dialogResult == DialogResult.Yes)
                    {
                        this.Save();
                        if (!this.IsDirty) this.CancelDirty(false);
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        this.CancelDirty(true);
                    }
                    else
                        return;
                }
                else
                    this.CancelDirty(false);
            }
            else
                this.Close(); //Unload this module
        }


        public void Loading()
        {
            try
            {
                this.GetMasterList();
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        public void New()
        {
            this.marketingMonitoringBLL.New();
            this.SetEditableMode(true);
        }

        public void Edit()
        {
            this.marketingMonitoringBLL.Edit();
            this.SetEditableMode(true);
        }

        public void Save()
        {
            this.marketingMonitoringBLL.Save();
        }

        public void Delete()
        {
            this.marketingMonitoringBLL.Delete();
        }

        public void Import()
        {
        }

        public void Export()
        {
            try
            {
                DataTable dataTableExport;

                if (this.ActiveControl.Equals(this.dataListViewMaster))
                    dataTableExport = this.dataListViewMaster.DataSource as DataTable;
                else
                    dataTableExport = this.dataListViewDetail.DataSource as DataTable;

                if (dataTableExport != null) CommonFormAction.Export(dataTableExport);


                //if (this.ActiveControl is DataListView)
                //{
                //    DataListView dataListView = this.ActiveControl as DataListView;
                //    if (dataListView != null)
                //    {
                //        DataTable dataTableExport;
                //        dataTableExport = dataListView.DataSource as DataTable;
                //        if (dataTableExport != null) CommonFormAction.Export(dataTableExport);
                //    }
                //}
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        public void Verify()
        {
            MessageBox.Show("Verify");
        }

        public void Print(PrintDestination printDestination)
        {
            MessageBox.Show("Print");

            PublicPrintObjectListView p = new PublicPrintObjectListView(this.dataListViewMaster);
            p.Show(this);


        }


        public void SearchText(string searchText)
        {
            CommonFormAction.OLVFilter(this.dataListViewMaster, searchText);
            CommonFormAction.OLVFilter(this.dataListViewDetail, searchText);
        }

        #endregion


        #endregion <Implement Interface>








        #region <Storage>
        private MarketingMonitoringBLL marketingMonitoringBLL;

        #endregion <Storage>

        public MarketingMonitoring()
        {
            try
            {
                InitializeComponent();

                this.buttonNaviBarHeaderVisibleBinding = this.buttonNaviBarHeader.DataBindings.Add("Visible", this.naviBarFilter, "Collapsed", true, DataSourceUpdateMode.OnPropertyChanged);
                this.buttonNaviBarHeaderVisibleBinding.Parse += new ConvertEventHandler(buttonNaviBarHeaderVisibleBinding_Parse);
                this.buttonNaviBarHeaderVisibleBinding.Format += new ConvertEventHandler(buttonNaviBarHeaderVisibleBinding_Format);

                this.buttonRefreshVisibleBinding = this.buttonRefresh.DataBindings.Add("Visible", this.naviBarFilter, "Collapsed", true, DataSourceUpdateMode.OnPropertyChanged);
                this.buttonRefreshVisibleBinding.Parse += new ConvertEventHandler(buttonNaviBarHeaderVisibleBinding_Parse);
                this.buttonRefreshVisibleBinding.Format += new ConvertEventHandler(buttonNaviBarHeaderVisibleBinding_Format);


                this.marketingMonitoringBLL = new MarketingMonitoringBLL();

                this.marketingMonitoringBLL.PropertyChanged += new PropertyChangedEventHandler(marketingMonitoringBLL_PropertyChanged);

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        void marketingMonitoringBLL_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                this.NotifyPropertyChanged(e.PropertyName);

                switch (e.PropertyName)
                {
                    case "MonitoringOption":
                        this.GetMasterList();
                        break;
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }

        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetMasterList();
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        private void MarketingMonitoring_Load(object sender, EventArgs e)
        {
            try
            {
                InitializeCommonControlBinding();

                InitializeReadOnlyModeBinding();

                this.GetMasterList();

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        #region <InitializeBinding>

        Binding buttonNaviBarHeaderVisibleBinding;
        Binding buttonRefreshVisibleBinding;
        Binding monitoringByBinding;

        private void InitializeCommonControlBinding()
        {

            ArrayList MonitoringOptions = new ArrayList();
            MonitoringOptions.Add(new MonitoringOption("View by Marketing Program", "MarketingMonitoringByProgram"));
            MonitoringOptions.Add(new MonitoringOption("View by Requested Customer", "MarketingMonitoringByCustomer"));
            this.toolStripComboBoxMonitoringBy.ComboBox.DataSource = MonitoringOptions;
            this.toolStripComboBoxMonitoringBy.ComboBox.DisplayMember = "DisplayMember";
            this.toolStripComboBoxMonitoringBy.ComboBox.ValueMember = "ValueMember";

            monitoringByBinding = this.toolStripComboBoxMonitoringBy.ComboBox.DataBindings.Add("SelectedValue", this.marketingMonitoringBLL, "MonitoringOption", true, DataSourceUpdateMode.OnPropertyChanged);
            this.monitoringByBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);


            #region Filter by MarketingProgram
            this.dataTreeListViewFilterMarketingProgram.KeyAspectName = "PrimaryFilterID";
            this.dataTreeListViewFilterMarketingProgram.ParentKeyAspectName = "AncestorID";
            this.dataTreeListViewFilterMarketingProgram.RootKeyValue = -1;

            this.dataTreeListViewFilterMarketingProgram.DataMember = "TableFilterMarketingProgram";
            this.dataTreeListViewFilterMarketingProgram.DataSource = new DataViewManager(this.marketingMonitoringBLL.DataSetFilter);

            this.dataTreeListViewFilterMarketingProgram.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterMarketingProgram.ExpandAll();

            #endregion Filter by MarketingProgram


            #region Filter by ItemCategory + ItemCommodity
            this.dataTreeListViewFilterCommodity.KeyAspectName = "PrimaryFilterID";
            this.dataTreeListViewFilterCommodity.ParentKeyAspectName = "AncestorID";
            this.dataTreeListViewFilterCommodity.RootKeyValue = -1;

            this.dataTreeListViewFilterCommodity.DataMember = "TableFilterCommodity";
            this.dataTreeListViewFilterCommodity.DataSource = new DataViewManager(this.marketingMonitoringBLL.DataSetFilter);

            this.dataTreeListViewFilterCommodity.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterCommodity.ExpandAll();

            #endregion Filter by ItemCategory + ItemCommodity


            #region Filter by CustomerChannel
            this.dataTreeListViewFilterCustomer.KeyAspectName = "PrimaryFilterID";
            this.dataTreeListViewFilterCustomer.ParentKeyAspectName = "AncestorID";
            this.dataTreeListViewFilterCustomer.RootKeyValue = -1;

            this.dataTreeListViewFilterCustomer.DataMember = "TableFilterCustomer";
            this.dataTreeListViewFilterCustomer.DataSource = new DataViewManager(this.marketingMonitoringBLL.DataSetFilter);

            this.dataTreeListViewFilterCustomer.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterCustomer.ExpandAll();

            #endregion Filter by CustomerChannel


            this.naviBarFilter.Bands[0].Text = "Filter by Commodity";
            this.naviBarFilter.Bands[1].Text = "Filter by Customer";
            this.naviBarFilter.Bands[2].Text = "Filter by Program";
            this.naviBarFilter.VisibleLargeButtons = 0;
            this.naviBarFilter.PopupHeight = this.naviBarFilter.Height + this.naviBarFilter.HeaderHeight + 5;


            this.dataTreeListViewFilterMarketingProgram.Columns[0].Width = this.naviBarFilter.Width - this.dataTreeListViewFilterMarketingProgram.Columns["V"].Width - 23;
            this.dataTreeListViewFilterCommodity.Columns[0].Width = this.naviBarFilter.Width - this.dataTreeListViewFilterCommodity.Columns["V"].Width - 23;
            this.dataTreeListViewFilterCustomer.Columns[0].Width = this.naviBarFilter.Width - this.dataTreeListViewFilterCustomer.Columns["V"].Width - 23;


            this.naviBarFilter.Bands[0].SmallImage = this.imageListSmall.Images[0];
            this.naviBarFilter.Bands[1].SmallImage = this.imageListSmall.Images[1];
            this.naviBarFilter.Bands[2].SmallImage = this.imageListSmall.Images[2];

            this.naviGroupDetails.DataBindings.Add("ExpandedHeight", this.numericUpDownSizingDetail, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
            this.numericUpDownSizingDetail.Minimum = this.naviGroupDetails.HeaderHeight * 2;
            this.numericUpDownSizingDetail.Maximum = this.naviGroupDetails.Height + this.dataListViewMaster.Height;

            this.naviBarJournal.Bands[0].Text = "Payment Journal";

        }

        private void CommonControl_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteState == BindingCompleteState.Exception) { GlobalExceptionHandler.ShowExceptionMessageBox(this, e.ErrorText); e.Cancel = true; }
        }

        private void dataTreeListViewFilter_Resize(object sender, EventArgs e)
        {
            if (sender.Equals(this.dataTreeListViewFilterMarketingProgram) && this.dataTreeListViewFilterMarketingProgram.Columns["PrimaryFilterOption"] != null)
            {
                this.dataTreeListViewFilterMarketingProgram.Columns["PrimaryFilterOption"].Width = 0;
                this.dataTreeListViewFilterMarketingProgram.ExpandAll();
            }

            if (sender.Equals(this.dataTreeListViewFilterCommodity) && this.dataTreeListViewFilterCommodity.Columns["PrimaryFilterOption"] != null)
            {
                this.dataTreeListViewFilterCommodity.Columns["PrimaryFilterOption"].Width = 0;
                this.dataTreeListViewFilterCommodity.ExpandAll();
            }

            if (sender.Equals(this.dataTreeListViewFilterCustomer) && this.dataTreeListViewFilterCustomer.Columns["PrimaryFilterOption"] != null)
            {
                this.dataTreeListViewFilterCustomer.Columns["PrimaryFilterOption"].Width = 0;
                this.dataTreeListViewFilterCustomer.ExpandAll();
            }
        }


        void buttonNaviBarHeaderVisibleBinding_Parse(object sender, ConvertEventArgs e)
        {
            e.Value = !(bool)e.Value;
        }

        void buttonNaviBarHeaderVisibleBinding_Format(object sender, ConvertEventArgs e)
        {
            e.Value = !(bool)e.Value;
        }


        private void InitializeReadOnlyModeBinding()
        {
            List<Control> controlList = GlobalStaticFunction.GetAllControls(this);

            //foreach (Control control in controlList)
            //{
            //    //if (control is TextBox) control.DataBindings.Add("Readonly", this, "ReadonlyMode");
            //    if (control is TextBox) control.DataBindings.Add("Enabled", this, "EditableMode");
            //    else if (control is ComboBox || control is DateTimePicker) control.DataBindings.Add("Enabled", this, "EditableMode");
            //    else if (control is DataGridView)
            //    {
            //        control.DataBindings.Add("Readonly", this, "ReadonlyMode");
            //        control.DataBindings.Add("AllowUserToAddRows", this, "EditableMode");
            //        control.DataBindings.Add("AllowUserToDeleteRows", this, "EditableMode");
            //    }
            //}

        }

        #endregion <InitializeBinding>

        private void buttonNaviBarHeader_Click(object sender, EventArgs e)
        {
            this.naviBarFilter.Collapsed = true;
        }

        private void naviBarModuleMaster_CollapsedChanged(object sender, EventArgs e)
        {
            this.dataTreeListViewFilterMarketingProgram.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterMarketingProgram.Columns[0].Width = this.dataTreeListViewFilterMarketingProgram.Columns[0].Width + (this.naviBarFilter.Collapsed ? -4 : 4);
            this.dataTreeListViewFilterMarketingProgram.ExpandAll();

            this.dataTreeListViewFilterCommodity.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterCommodity.Columns[0].Width = this.dataTreeListViewFilterCommodity.Columns[0].Width + (this.naviBarFilter.Collapsed ? -4 : 4);
            this.dataTreeListViewFilterCommodity.ExpandAll();

            this.dataTreeListViewFilterCustomer.Columns["PrimaryFilterOption"].Width = 0;
            this.dataTreeListViewFilterCustomer.Columns[0].Width = this.dataTreeListViewFilterCustomer.Columns[0].Width + (this.naviBarFilter.Collapsed ? -4 : 4);
            this.dataTreeListViewFilterCustomer.ExpandAll();
        }


        private void naviBarModuleMaster_ActiveBandChanged(object sender, EventArgs e)
        {
            try
            {
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void GetMasterList()
        {
            this.dataListViewMaster.Visible = false;
            this.dataListViewDetail.ClearObjects();
            this.dataListViewMaster.Reset();

            DataTable dataTableMasterList = this.marketingMonitoringBLL.GetMasterList();

            int i = -1;
            columnPaymentTermIncentiveMarketingProgramID = -1;
            columnPaymentPeriodMarketingProgramID = -1;
            columnAmountPaid = -1;
            columnBalance = -1;

            columnApplyItemMarketingProgramID = -1;
            columnApplyChannelMarketingProgramID = -1;

            foreach (DataColumn dataColumn in dataTableMasterList.Columns)
            {
                OLVColumn olvColumn = NewOLVColumn(dataColumn); i++;



                if (dataColumn.DataType == typeof(System.Int32))
                {

                    if (dataColumn.ColumnName == "PaymentTermIncentiveMarketingProgramID") columnPaymentTermIncentiveMarketingProgramID = i;
                    if (dataColumn.ColumnName == "PaymentPeriodMarketingProgramID") columnPaymentPeriodMarketingProgramID = i;

                    if (this.marketingMonitoringBLL.MonitoringOption == "MarketingMonitoringByProgram" && dataColumn.ColumnName == "ApplyChannelMarketingProgramID") columnApplyChannelMarketingProgramID = i;
                    if (this.marketingMonitoringBLL.MonitoringOption == "MarketingMonitoringByProgram" && dataColumn.ColumnName == "ApplyItemMarketingProgramID") columnApplyItemMarketingProgramID = i;
                }

                if (dataColumn.DataType == typeof(System.Double))
                {
                    if (dataColumn.ColumnName == "Amount Paid") columnAmountPaid = i;
                    if (dataColumn.ColumnName == "Balance") columnBalance = i;

                    if (columnPaymentTermIncentiveMarketingProgramID != -1 && i >= columnPaymentTermIncentiveMarketingProgramID) olvColumn.HeaderForeColor = Color.FromName("green");
                    if (columnPaymentPeriodMarketingProgramID != -1 && i >= columnPaymentPeriodMarketingProgramID) olvColumn.HeaderForeColor = Color.FromName("blue");

                    if (dataColumn.ColumnName == "% Performance" || dataColumn.ColumnName == "% Budget") { olvColumn.IsHeaderVertical = true; olvColumn.HeaderForeColor = Color.FromName("red"); }
                    if (dataColumn.ColumnName == "Incentive Amount") olvColumn.HeaderForeColor = Color.FromName("black");
                    if (dataColumn.ColumnName == "Amount Paid") olvColumn.HeaderForeColor = Color.FromName("black");
                    if (dataColumn.ColumnName == "Balance") olvColumn.HeaderForeColor = Color.FromName("black");
                }

                if (dataColumn.DataType == typeof(System.Boolean))
                {

                    if (columnApplyChannelMarketingProgramID != -1 && i >= columnApplyChannelMarketingProgramID) olvColumn.HeaderForeColor = Color.FromName("magenta");
                    if (columnApplyItemMarketingProgramID != -1 && i >= columnApplyItemMarketingProgramID) olvColumn.HeaderForeColor = Color.FromName("black");

                }

                this.dataListViewMaster.Columns.Add(olvColumn);
            }

            this.dataListViewMaster.HeaderMaximumHeight = 86;
            this.dataListViewMaster.AutoGenerateColumns = false;
            this.dataListViewMaster.DataSource = dataTableMasterList;

            this.ResizeOLVColumn(this.dataListViewMaster, dataTableMasterList.Rows.Count);

            this.dataListViewMaster.Visible = true;

            if (this.dataListViewMaster.Items.Count > 0) this.dataListViewMaster.SelectedIndex = 0;
        }

        private void dataListViewMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int filterID;

                    if (int.TryParse(row.Row[(this.marketingMonitoringBLL.MonitoringOption == "MarketingMonitoringByProgram" ? "MarketingProgramID" : "CustomerID")].ToString(), out filterID))
                    {
                        if (this.dataListViewDetail.Tag == null || this.dataListViewDetail.Tag.ToString() != filterID.ToString())
                        {
                            this.dataListViewDetail.Tag = filterID.ToString();

                            this.dataListViewDetail.Visible = false;
                            this.dataListViewDetail.ClearObjects();
                            this.dataListViewDetail.Reset();

                            DataTable dataTableDetailList = this.marketingMonitoringBLL.GetDetailList(filterID);

                            foreach (DataColumn dataColumn in dataTableDetailList.Columns)
                            {
                                this.dataListViewDetail.Columns.Add(NewOLVColumn(dataColumn));
                            }

                            this.dataListViewDetail.HeaderMaximumHeight = 86;
                            this.dataListViewDetail.AutoGenerateColumns = false;
                            this.dataListViewDetail.DataSource = dataTableDetailList;

                            this.ResizeOLVColumn(this.dataListViewDetail, dataTableDetailList.Rows.Count);


                            if (this.marketingMonitoringBLL.MonitoringOption == "MarketingMonitoringByProgram")
                            {
                                ((OLVColumn)this.dataListViewDetail.Columns["Program Type"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Reference"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Reference Code"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Program Name"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Sub Name"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Program Group"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Begining Month"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Begining Date"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Ending Date"]).MinimumWidth = 0;

                                this.dataListViewDetail.Columns["Program Type"].Width = 0;
                                this.dataListViewDetail.Columns["Reference"].Width = 0;
                                this.dataListViewDetail.Columns["Reference Code"].Width = 0;
                                this.dataListViewDetail.Columns["Program Name"].Width = 0;
                                this.dataListViewDetail.Columns["Sub Name"].Width = 0;
                                this.dataListViewDetail.Columns["Program Group"].Width = 0;
                                this.dataListViewDetail.Columns["Begining Month"].Width = 0;
                                this.dataListViewDetail.Columns["Begining Date"].Width = 0;
                                this.dataListViewDetail.Columns["Ending Date"].Width = 0;

                                this.dataListViewDetail.Columns["Customer Code"].Width = this.dataListViewDetail.Columns["Customer Code"].Width + 15;
                            }
                            else
                            {
                                ((OLVColumn)this.dataListViewDetail.Columns["Customer Code"]).MinimumWidth = 0;
                                ((OLVColumn)this.dataListViewDetail.Columns["Customer Name"]).MinimumWidth = 0;

                                this.dataListViewDetail.Columns["Customer Code"].Width = 0;
                                this.dataListViewDetail.Columns["Customer Name"].Width = 0;
                            }


                            this.dataListViewDetail.Visible = true;

                            if (this.dataListViewDetail.Items.Count > 0) this.dataListViewDetail.SelectedIndex = 0;

                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }




        private int columnPaymentTermIncentiveMarketingProgramID = -1;
        private int columnPaymentPeriodMarketingProgramID = -1;
        private int columnAmountPaid = -1;
        private int columnBalance = -1;

        private int columnApplyChannelMarketingProgramID = -1;
        private int columnApplyItemMarketingProgramID = -1;

        private OLVColumn NewOLVColumn(DataColumn dataColumn)
        {
            OLVColumn olvColumn = new OLVColumn(dataColumn.ColumnName.Length >= 6 && dataColumn.ColumnName.Substring(0, 6) == "ZTotal" ? "Total" : dataColumn.ColumnName, dataColumn.ColumnName);
            olvColumn.Name = dataColumn.ColumnName;
            olvColumn.DataType = dataColumn.DataType;


            if (dataColumn.DataType == typeof(System.String))
            {
                olvColumn.WordWrap = true;
                olvColumn.MinimumWidth = 30;
                if (dataColumn.ColumnName == "Begining Month")
                {
                    olvColumn.HeaderTextAlign = HorizontalAlignment.Center;
                    olvColumn.TextAlign = HorizontalAlignment.Center;
                }
            }

            if (dataColumn.DataType == typeof(System.DateTime))
            {
                olvColumn.AspectToStringFormat = "{0:dd/MM/yy}";
                olvColumn.HeaderTextAlign = HorizontalAlignment.Center;
                olvColumn.TextAlign = HorizontalAlignment.Center;
                olvColumn.MinimumWidth = 65;
            }


            if (dataColumn.DataType == typeof(System.Double))
            {
                olvColumn.AspectToStringFormat = "{0:#,#}";
                olvColumn.HeaderTextAlign = HorizontalAlignment.Right;
                olvColumn.TextAlign = HorizontalAlignment.Right;
                olvColumn.MinimumWidth = olvColumn.Name == "% Performance" || olvColumn.Name == "% Budget" ? 25 : 65;
                olvColumn.Groupable = false;
            }

            if (dataColumn.DataType == typeof(System.Boolean))
            {
                olvColumn.CheckBoxes = true;
                olvColumn.HeaderTextAlign = HorizontalAlignment.Center;
                olvColumn.TextAlign = HorizontalAlignment.Center;
                olvColumn.IsHeaderVertical = true;
                olvColumn.MinimumWidth = 45;
            }

            if (dataColumn.DataType != typeof(System.Boolean)) olvColumn.Renderer = null;

            return olvColumn;
        }


        private void ResizeOLVColumn(DataListView dataListView, int rowCount)
        {
            foreach (OLVColumn olvColumn in dataListView.Columns)
            {
                if (olvColumn.DataType == typeof(System.Int32)) { olvColumn.Hideable = true; olvColumn.IsVisible = false; olvColumn.Width = 0; }
                else
                    if (olvColumn.DataType == typeof(System.Boolean)) { olvColumn.MinimumWidth = 25; olvColumn.Width = 25; }
                    else olvColumn.AutoResize(rowCount != 0 || olvColumn.Name == "% Performance" || olvColumn.Name == "% Budget" ? ColumnHeaderAutoResizeStyle.ColumnContent : ColumnHeaderAutoResizeStyle.HeaderSize);

                if ((olvColumn.Name == "Territory" || olvColumn.Name == "Customer Name") && olvColumn.Width > 150) { olvColumn.Width = olvColumn.Width - 80; }
            }
        }


        private void numericUpDownSizingDetail_ValueChanged(object sender, EventArgs e)
        {
            this.naviGroupDetails.Expand();
        }

        private void naviGroupDetails_HeaderMouseClick(object sender, MouseEventArgs e)
        {
            this.numericUpDownSizingDetail.Visible = this.naviGroupDetails.Expanded;
        }




        private void dataListViewMaster_FormatCell(object sender, FormatCellEventArgs e)
        {

            if (e.Column.Name == "Incentive Amount") e.SubItem.ForeColor = Color.FromName("black");
            if (e.Column.Name == "Amount Paid") e.SubItem.ForeColor = Color.FromName("black");
            if (e.Column.Name == "Balance") e.SubItem.ForeColor = Color.FromName("black");
            if (e.Column.Name == "% Performance" || e.Column.Name == "% Budget") e.SubItem.ForeColor = Color.FromName("red");


            if (columnPaymentTermIncentiveMarketingProgramID != -1 && e.ColumnIndex >= columnPaymentTermIncentiveMarketingProgramID && e.ColumnIndex < columnPaymentPeriodMarketingProgramID) e.SubItem.ForeColor = Color.FromName("green");
            if (columnPaymentPeriodMarketingProgramID != -1 && e.ColumnIndex >= columnPaymentPeriodMarketingProgramID && e.ColumnIndex < columnAmountPaid) e.SubItem.ForeColor = Color.FromName("blue");
            if (columnApplyChannelMarketingProgramID != -1 && e.ColumnIndex >= columnApplyChannelMarketingProgramID && e.ColumnIndex < columnApplyItemMarketingProgramID) e.SubItem.ForeColor = Color.FromName("cyan");
            if (columnApplyChannelMarketingProgramID != -1 && e.ColumnIndex >= columnApplyItemMarketingProgramID) e.SubItem.ForeColor = Color.FromName("magenta");

            if (e.Column.Name == "Program Type" || e.Column.Name == "Territory")
            {
                try
                {
                    DataRowView dataRowView = e.Model as DataRowView;
                    if (dataRowView != null)
                    {
                        double balance;
                        if (double.TryParse(dataRowView.Row["Balance"].ToString(), out balance) && Math.Round(balance, 0) != 0)
                            e.SubItem.Decoration = new ImageDecoration(ResourceIcon.RedStar.ToBitmap());
                        else
                            e.SubItem.Decoration = null;
                    }
                }
                catch { }
            }

        }

        private void dataListViewDetail_FormatCell(object sender, FormatCellEventArgs e)
        {
            try
            {
                if ((this.marketingMonitoringBLL.MonitoringOption != "MarketingMonitoringByProgram" && e.Column.Name == "Program Type") || (this.marketingMonitoringBLL.MonitoringOption == "MarketingMonitoringByProgram" && e.Column.Name == "Customer Code"))
                {

                    DataRowView dataRowView = e.Model as DataRowView;
                    if (dataRowView != null)
                    {
                        double balance;
                        if (double.TryParse(dataRowView.Row["Balance"].ToString(), out balance) && Math.Round(balance, 0) != 0)
                            e.SubItem.Decoration = new ImageDecoration(ResourceIcon.RedStar.ToBitmap());
                        else
                            e.SubItem.Decoration = null;
                    }

                }
            }
            catch { }
        }


        private void dataListViewMaster_SubItemChecking(object sender, SubItemCheckingEventArgs e)
        {
            e.Canceled = true;
        }

        private void dataListViewDetail_SubItemChecking(object sender, SubItemCheckingEventArgs e)
        {
            e.Canceled = true;
        }









        private void splitContainerJournal_SizeChanged(object sender, EventArgs e)
        {
            if (this.splitContainerJournal.Height > 10)
            {
                this.splitContainerJournal.SplitterDistance = (int)(this.splitContainerJournal.Height * 60 / 100);
                this.splitContainerJournal.SplitterWidth = 1;
            }
        }

        private void toolStripButtonShowJournal_Click(object sender, EventArgs e)
        {
            this.naviBarJournal.Collapsed = !this.naviBarJournal.Collapsed;
            this.toolStripButtonShowJournal.Image = this.naviBarJournal.Collapsed ? ResourceIcon.chevron_Left.ToBitmap() : ResourceIcon.chevron_Right.ToBitmap();
        }


        private void naviBarJournal_Resize(object sender, EventArgs e)
        {
            this.naviBarJournal.PopupHeight = this.naviBarJournal.Height;
        }


        private void dataListViewDetail_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int marketingProgramID; int customerID;

                    if (int.TryParse(row.Row["MarketingProgramID"].ToString(), out marketingProgramID) && int.TryParse(row.Row["CustomerID"].ToString(), out customerID))
                    {
                        if (this.dataListViewIncentiveJournal.Tag == null || this.dataListViewIncentiveJournal.Tag.ToString() != marketingProgramID.ToString() + "--" + customerID.ToString())
                        {
                            this.dataListViewIncentiveJournal.Tag = marketingProgramID.ToString() + "--" + customerID.ToString();

                            DataTable dataTableMarketingIncentiveJournal = this.marketingMonitoringBLL.GetMarketingIncentiveJournal(marketingProgramID, customerID);

                            this.dataListViewIncentiveJournal.AutoGenerateColumns = false;
                            this.dataListViewIncentiveJournal.DataSource = dataTableMarketingIncentiveJournal;

                            if (this.dataListViewIncentiveJournal.Items.Count > 0) this.dataListViewIncentiveJournal.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void dataListViewIncentiveJournal_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int marketingIncentiveID; int marketingIncentiveSerialID;

                    if (int.TryParse(row.Row["MarketingIncentiveID"].ToString(), out marketingIncentiveID) && int.TryParse(row.Row["MarketingIncentiveSerialID"].ToString(), out marketingIncentiveSerialID))
                    {
                        if (this.dataListViewPaymentJournal.Tag == null || this.dataListViewPaymentJournal.Tag.ToString() != marketingIncentiveID.ToString() + "--" + marketingIncentiveSerialID.ToString())
                        {
                            this.dataListViewPaymentJournal.Tag = marketingIncentiveID.ToString() + "--" + marketingIncentiveSerialID.ToString();

                            DataTable dataTableMarketingIncentiveJournal = this.marketingMonitoringBLL.GetMarketingPaymentJournal(marketingIncentiveID, marketingIncentiveSerialID);

                            this.dataListViewPaymentJournal.AutoGenerateColumns = false;
                            this.dataListViewPaymentJournal.DataSource = dataTableMarketingIncentiveJournal;

                            if (this.dataListViewPaymentJournal.Items.Count > 0) this.dataListViewPaymentJournal.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void toolStripButtonPivotJournal_Click(object sender, EventArgs e)
        {
            this.ExcelPivotJournal();
        }






        #region Excel Pivot Data

        private object useDefault = Type.Missing;

        private string GetExcelColumnName(int columnNumber)
        {
            int dividend = columnNumber;
            string columnName = String.Empty;
            int modulo;

            while (dividend > 0)
            {
                modulo = (dividend - 1) % 26;
                columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
                dividend = (int)((dividend - modulo) / 26);
            }

            return columnName;
        }

        /// <summary>
        /// Helper method to set a value on a single cell.
        /// </summary>
        private void SetCellValue(OfficeExcel.Worksheet targetSheet, string cell, object value)
        {
            targetSheet.get_Range(cell, useDefault).set_Value(OfficeExcel.XlRangeValueDataType.xlRangeValueDefault, value);
        }


        private void ExcelPivotJournal()
        {

            // Declare variables that hold references to excel objects
            OfficeExcel.Application excelApplication = null;
            OfficeExcel.Workbook excelWorkBook = null;
            OfficeExcel.Worksheet targetSheet = null;
            OfficeExcel.Worksheet pivotSheet = null;
            OfficeExcel.PivotTable pivotTable = null;
            OfficeExcel.Range pivotData = null;
            OfficeExcel.Range pivotDestination = null;
            OfficeExcel.PivotField salesRegion = null;
            OfficeExcel.PivotField salesAmount = null;

            // Declare helper variables
            string workBookName = @"C:\Temp\PivotTableSample.xlsx";
            string pivotTableName = @"Customer versus Program";
            string workSheetName = @"Customer in Program";

            try
            {
                DataTable tableMarketingMasterJournal = this.marketingMonitoringBLL.GetMarketingMasterJournal();

                if (tableMarketingMasterJournal.Rows.Count <= 0) throw new Exception("There is no data to show.");






                object[,] arr = new object[tableMarketingMasterJournal.Rows.Count, tableMarketingMasterJournal.Columns.Count];
                for (int rowIndex = 0; rowIndex < tableMarketingMasterJournal.Rows.Count; rowIndex++)
                {
                    for (int columnIndex = 0; columnIndex < tableMarketingMasterJournal.Columns.Count; columnIndex++)
                    {
                        arr[rowIndex, columnIndex] = (tableMarketingMasterJournal.Columns[columnIndex].ColumnName == "PaymentPeriod" ? "'" : "") + tableMarketingMasterJournal.Rows[rowIndex][columnIndex];
                    }
                }




                // Create an instance of Excel
                excelApplication = new OfficeExcel.Application();
                //excelApplication.Visible = true;//Le Minh Hiep

                //Create a workbook and add a worksheet.
                excelWorkBook = excelApplication.Workbooks.Add(OfficeExcel.XlWBATemplate.xlWBATWorksheet);
                targetSheet = (OfficeExcel.Worksheet)(excelWorkBook.Worksheets[1]);
                targetSheet.Name = "Filter Description";
                var startCell = (OfficeExcel.Range)targetSheet.Cells[1, 1];
                var endCell = (OfficeExcel.Range)targetSheet.Cells[4, 2];
                var writeRange = targetSheet.Range[startCell, endCell];

                writeRange.Value2 = this.marketingMonitoringBLL.FilterDescription();
                targetSheet.get_Range("A1", "B4").Columns.AutoFit();
                targetSheet.get_Range("A1", "B4").Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.FromArgb(221, 217, 195));


                excelWorkBook.Worksheets.Add(useDefault, targetSheet);
                targetSheet = (OfficeExcel.Worksheet)(excelWorkBook.Worksheets[2]);
                targetSheet.Name = workSheetName;


                for (int columnIndex = 0; columnIndex < tableMarketingMasterJournal.Columns.Count; columnIndex++)
                {
                    this.SetCellValue(targetSheet, this.GetExcelColumnName(columnIndex + 1) + "1", tableMarketingMasterJournal.Columns[columnIndex].ColumnName);
                }



                startCell = (OfficeExcel.Range)targetSheet.Cells[2, 1];
                endCell = (OfficeExcel.Range)targetSheet.Cells[tableMarketingMasterJournal.Rows.Count + 1, tableMarketingMasterJournal.Columns.Count];
                writeRange = targetSheet.Range[startCell, endCell];

                writeRange.Value2 = arr;





                for (int columnIndex = 0; columnIndex < tableMarketingMasterJournal.Columns.Count; columnIndex++)
                {
                    if (tableMarketingMasterJournal.Columns[columnIndex].DataType == typeof(System.DateTime) || tableMarketingMasterJournal.Columns[columnIndex].DataType == typeof(System.Double))
                        ((OfficeExcel.Range)targetSheet.Cells[2, columnIndex + 1]).EntireColumn.NumberFormat = tableMarketingMasterJournal.Columns[columnIndex].DataType == typeof(System.DateTime) ? "dd/mm/yyyy" : "#,###";


                }


                targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + (tableMarketingMasterJournal.Rows.Count + 1).ToString()).Columns.AutoFit();
                targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + "1").Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.FromArgb(197, 190, 151));
                targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + "1").RowHeight = targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + "1").RowHeight + 8;
                targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + "1").VerticalAlignment = OfficeExcel.XlVAlign.xlVAlignCenter;



                //#region Pivot table
                //// Select a range of data for the Pivot Table.
                //pivotData = targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + (tableMarketingMasterJournal.Rows.Count + 1).ToString());

                //// Select location of the Pivot Table.
                //excelWorkBook.Worksheets.Add(useDefault, targetSheet);//OfficeExcel.XlWBATemplate.xlWBATWorksheet);
                //pivotSheet = (OfficeExcel.Worksheet)(excelWorkBook.Worksheets[3]);
                //pivotSheet.Name = "Pivot Report";
                //pivotSheet.Activate();
                //pivotDestination = pivotSheet.get_Range("A1", useDefault);

                //// Add a pivot table to the work sheet.
                //excelWorkBook.PivotTableWizard(
                //    OfficeExcel.XlPivotTableSourceType.xlDatabase,
                //    pivotData,
                //    pivotDestination,
                //    pivotTableName,
                //    true,
                //    true,
                //    true,
                //    true,
                //    useDefault,
                //    useDefault,
                //    false,
                //    false,
                //    OfficeExcel.XlOrder.xlDownThenOver,
                //    0,
                //    useDefault,
                //    useDefault
                //    );

                //// Set variables for used to manipulate the Pivot Table.
                //pivotTable =
                //    (OfficeExcel.PivotTable)pivotSheet.PivotTables(pivotTableName);

                //salesAmount = ((OfficeExcel.PivotField)pivotTable.PivotFields(13));

                //// Format the Pivot Table.
                //pivotTable.Format(OfficeExcel.XlPivotFormatType.xlPTClassic);
                //pivotTable.InGridDropZones = false;


                //////Set column field
                ////OfficeExcel.PivotField fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("Reference"));
                ////fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                ////fld.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
                ////fld.NumberFormat = "#,##0_);[Red](#,##0)";


                //OfficeExcel.PivotField fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("Reference")); // Set a column field.
                //fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlColumnField;


                //fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("CustomerCode")); // Set a row field.
                //fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlRowField;

                //fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("MarketingProgramSubName")); // Set a value field.
                //fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                //fld.Function = OfficeExcel.XlConsolidationFunction.xlCount;


                ////// Set Sum of Sales Amount as a Value Field.
                ////salesAmount.Orientation =
                ////    OfficeExcel.XlPivotFieldOrientation.xlDataField;
                ////salesAmount.Function = OfficeExcel.XlConsolidationFunction.xlSum;

                //#endregion Pivot Table



                #region New Pivot Table
                // Select a range of data for the Pivot Table.
                pivotData = targetSheet.get_Range("A1", this.GetExcelColumnName(tableMarketingMasterJournal.Columns.Count) + (tableMarketingMasterJournal.Rows.Count + 1).ToString());

                // Select location of the Pivot Table.
                excelWorkBook.Worksheets.Add(useDefault, targetSheet);//OfficeExcel.XlWBATemplate.xlWBATWorksheet);
                pivotSheet = (OfficeExcel.Worksheet)(excelWorkBook.Worksheets[3]);
                pivotSheet.Name = "New Pivot Report";
                pivotSheet.Activate();
                pivotDestination = pivotSheet.get_Range("A1", useDefault);

                // Add a pivot table to the work sheet.
                excelWorkBook.PivotTableWizard(
                    OfficeExcel.XlPivotTableSourceType.xlDatabase,
                    pivotData,
                    pivotDestination,
                    "Payment Report",
                    true,
                    true,
                    true,
                    true,
                    useDefault,
                    useDefault,
                    false,
                    false,
                    OfficeExcel.XlOrder.xlDownThenOver,
                    0,
                    useDefault,
                    useDefault
                    );

                // Set variables for used to manipulate the Pivot Table.
                pivotTable =
                    (OfficeExcel.PivotTable)pivotSheet.PivotTables("Payment Report");

                salesAmount = ((OfficeExcel.PivotField)pivotTable.PivotFields(13));

                

                ////Set column field
                //OfficeExcel.PivotField fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("Reference"));
                //fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                //fld.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
                //fld.NumberFormat = "#,##0_);[Red](#,##0)";


                //////fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("Reference")); // Set a column field.
                //////fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlColumnField;


                OfficeExcel.PivotField fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("MarketingProgramSubName")); // Set a row field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlRowField;

                fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("PaymentTypeName")); // Set a row field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlRowField;

                fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("PaymentPeriod")); // Set a row field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlRowField;



                fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("SalesAmount")); // Set a value field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                fld.Function = OfficeExcel.XlConsolidationFunction.xlSum;
                fld.NumberFormat = "#,###";

                fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("IncentiveAmount")); // Set a value field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                fld.Function = OfficeExcel.XlConsolidationFunction.xlSum;
                fld.NumberFormat = "#,###";

                fld = ((OfficeExcel.PivotField)pivotTable.PivotFields("PaidAmount")); // Set a value field.
                fld.Orientation = OfficeExcel.XlPivotFieldOrientation.xlDataField;
                fld.Function = OfficeExcel.XlConsolidationFunction.xlSum;
                fld.NumberFormat = "#,###";


                //// Set Sum of Sales Amount as a Value Field.
                //salesAmount.Orientation =
                //    OfficeExcel.XlPivotFieldOrientation.xlDataField;
                //salesAmount.Function = OfficeExcel.XlConsolidationFunction.xlSum;



                //// Format the Pivot Table.
                pivotTable.Format(OfficeExcel.XlPivotFormatType.xlPTClassic);
                pivotTable.InGridDropZones = false;
                #endregion New Pivot Table



                //// Save the workbook.
                //excelWorkBook.SaveAs(workBookName, useDefault, useDefault,
                //    useDefault, useDefault, useDefault,
                //    XlSaveAsAccessMode.xlNoChange, useDefault, useDefault,
                //    useDefault, useDefault, useDefault);   //Le Minh Hiep

                excelApplication.Visible = true;//Le Minh Hiep
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
            finally
            {
                // Release the references to the Excel objects.
                salesAmount = null;
                salesRegion = null;
                pivotDestination = null;
                pivotData = null;
                pivotTable = null;
                targetSheet = null;

                // Release the Workbook object.
                if (excelWorkBook != null)
                    excelWorkBook = null;

                //// Release the ApplicationClass object.
                //if (excelApplication != null)
                //{
                //    excelApplication.Quit();
                //    excelApplication = null;
                //}//Le Minh Hiep

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }



        #endregion Excel Pivot

        private void toolStripButtonMasterJournal_Click(object sender, EventArgs e)
        {

        }








    }


    public class MonitoringOption
    {
        private string displayMember;
        private string valueMember;

        public MonitoringOption(string displayMember, string valueMember)
        {
            this.displayMember = displayMember;
            this.valueMember = valueMember;
        }

        public string DisplayMember
        {

            get
            {
                return displayMember;
            }
        }

        public string ValueMember
        {
            get
            {
                return valueMember;
            }
        }



    }


}
